<template>
  <view class="account-form">
    <!-- 表单头部 -->
    <view class="form-header">
      <text class="form-title">{{ isEdit ? '编辑账号' : '添加账号' }}</text>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <!-- 基本信息 -->
      <view class="form-section">
        <text class="section-title">基本信息</text>

        <view class="form-group">
          <text class="form-label">账号标题 <text class="required">*</text></text>
          <input
            class="form-input"
            v-model="formData.title"
            placeholder="如：QQ、微信、银行卡等"
            :maxlength="50"
          />
        </view>

        <view class="form-group">
          <text class="form-label">分类</text>
          <view class="category-selector" @click="showCategoryPicker">
            <text class="category-text" :class="{ placeholder: !selectedCategory }">
              {{ selectedCategory ? selectedCategory.name : '选择分类' }}
            </text>
            <text class="selector-arrow">›</text>
          </view>
        </view>

        <view class="form-group">
          <text class="form-label">网站地址</text>
          <input
            class="form-input"
            v-model="formData.website"
            placeholder="如：https://www.qq.com"
            :maxlength="200"
          />
        </view>
      </view>

      <!-- 登录信息 -->
      <view class="form-section">
        <text class="section-title">登录信息</text>

        <view class="form-group">
          <text class="form-label">用户名/邮箱/手机号</text>
          <input
            class="form-input"
            v-model="formData.username"
            placeholder="登录用的用户名、邮箱或手机号"
            :maxlength="100"
          />
        </view>

        <view class="form-group">
          <text class="form-label">密码</text>
          <view class="password-input-wrapper">
            <input
              class="form-input password-input"
              v-model="formData.password"
              :password="!showPassword"
              placeholder="登录密码"
              :maxlength="100"
            />
            <view class="password-actions">
              <view class="action-btn" @click="togglePasswordVisibility">
                <text class="action-icon">{{ showPassword ? '🙈' : '👁️' }}</text>
              </view>
              <view class="action-btn" @click="showPasswordGenerator">
                <text class="action-icon">🎲</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 安全设置 -->
      <view class="form-section">
        <text class="section-title">安全设置</text>

        <view class="form-group">
          <text class="form-label">过期时间</text>
          <view class="date-selector" @click="showDatePicker">
            <text class="date-text" :class="{ placeholder: !formData.expires_at }">
              {{ formData.expires_at ? formatDate(formData.expires_at) : '选择过期时间（可选）' }}
            </text>
            <text class="selector-arrow">›</text>
          </view>
        </view>

        <view class="form-group">
          <view class="form-switches">
            <view class="switch-item" @click="toggleFavorite">
              <text class="switch-label">添加到收藏</text>
              <text class="switch-icon">{{ formData.is_favorite ? '⭐' : '☆' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 备注信息 -->
      <view class="form-section">
        <text class="section-title">备注信息</text>

        <view class="form-group">
          <text class="form-label">备注</text>
          <textarea
            class="form-textarea"
            v-model="formData.notes"
            placeholder="其他需要记录的信息"
            :maxlength="500"
          />
        </view>
      </view>
    </view>

    <!-- 表单底部 -->
    <view class="form-footer">
      <button class="cancel-btn" @click="handleCancel">
        取消
      </button>
      <button
        class="save-btn"
        :disabled="!canSave || isLoading"
        @click="handleSave"
      >
        {{ isLoading ? '保存中...' : '保存' }}
      </button>
    </view>

    <!-- 分类选择器 -->
    <uni-popup ref="categoryPopup" type="bottom" safe-area>
      <view class="category-picker">
        <view class="picker-header">
          <text class="picker-title">选择分类</text>
          <view class="picker-close" @click="hideCategoryPicker">
            <text>完成</text>
          </view>
        </view>
        <scroll-view class="picker-content" scroll-y>
          <view
            v-for="category in categories"
            :key="category.id"
            class="category-option"
            :class="{ active: selectedCategory?.id === category.id }"
            @click="selectCategory(category)"
          >
            <text class="category-icon">{{ getCategoryIcon(category.icon) }}</text>
            <text class="category-name">{{ category.name }}</text>
            <text v-if="selectedCategory?.id === category.id" class="selected-icon">✓</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 日期选择器 -->
    <uni-popup ref="datePopup" type="bottom" safe-area>
      <view class="date-picker">
        <view class="picker-header">
          <view class="picker-action" @click="clearDate">
            <text>清除</text>
          </view>
          <text class="picker-title">选择过期时间</text>
          <view class="picker-action" @click="hideDatePicker">
            <text>确定</text>
          </view>
        </view>
        <picker-view class="picker-view" :value="datePickerValue" @change="onDateChange">
          <picker-view-column>
            <view v-for="(year, index) in years" :key="index" class="picker-item">
              <text>{{ year }}年</text>
            </view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="(month, index) in months" :key="index" class="picker-item">
              <text>{{ month }}月</text>
            </view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="(day, index) in days" :key="index" class="picker-item">
              <text>{{ day }}日</text>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>

    <!-- 密码生成器 -->
    <uni-popup ref="generatorPopup" type="center" safe-area>
      <view class="generator-popup">
        <password-generator @use="useGeneratedPassword" @generated="onPasswordGenerated" />
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import type { Account } from '@/api/account'
import type { Category } from '@/api/category'
import { useCategoryStore } from '@/store'
import PasswordGenerator from '../password-generator/index.vue'

interface AccountFormProps {
  account?: Account | null
  isEdit?: boolean
}

interface AccountFormEmits {
  (event: 'save', data: Partial<Account>): void
  (event: 'cancel'): void
}

const props = withDefaults(defineProps<AccountFormProps>(), {
  account: null,
  isEdit: false
})

const emit = defineEmits<AccountFormEmits>()

// Store
const categoryStore = useCategoryStore()

// 页面引用
const categoryPopup = ref()
const datePopup = ref()
const generatorPopup = ref()

// 响应式数据
const showPassword = ref(false)
const isLoading = ref(false)
const selectedCategory = ref<Category | null>(null)

// 表单数据
const formData = ref({
  title: '',
  website: '',
  username: '',
  password: '',
  notes: '',
  category_id: 0,
  is_favorite: false,
  expires_at: ''
})

// 日期选择器数据
const datePickerValue = ref([0, 0, 0])
const years = ref<number[]>([])
const months = ref<number[]>([])
const days = ref<number[]>([])

// 计算属性
const categories = computed(() => {
  return categoryStore.activeCategories
})

const canSave = computed(() => {
  return formData.value.title.trim().length > 0
})

// 监听
watch(() => props.account, (newAccount) => {
  if (newAccount) {
    initFormData(newAccount)
  } else {
    resetFormData()
  }
}, { immediate: true })

// 页面加载
onMounted(() => {
  initDatePicker()
  loadCategories()
})

// 初始化日期选择器
const initDatePicker = () => {
  const currentYear = new Date().getFullYear()
  years.value = Array.from({ length: 10 }, (_, i) => currentYear + i)
  months.value = Array.from({ length: 12 }, (_, i) => i + 1)
  updateDays()
}

// 更新天数
const updateDays = () => {
  const year = years.value[datePickerValue.value[0]]
  const month = months.value[datePickerValue.value[1]]
  const daysInMonth = new Date(year, month, 0).getDate()
  days.value = Array.from({ length: daysInMonth }, (_, i) => i + 1)
}

// 初始化表单数据
const initFormData = (account: Account) => {
  formData.value = {
    title: account.title || '',
    website: account.website || '',
    username: account.username || '',
    password: account.password || '',
    notes: account.notes || '',
    category_id: account.category_id || 0,
    is_favorite: account.is_favorite || false,
    expires_at: account.expires_at || ''
  }

  if (account.category) {
    selectedCategory.value = account.category
  }
}

// 重置表单数据
const resetFormData = () => {
  formData.value = {
    title: '',
    website: '',
    username: '',
    password: '',
    notes: '',
    category_id: 0,
    is_favorite: false,
    expires_at: ''
  }
  selectedCategory.value = null
}

// 加载分类列表
const loadCategories = async () => {
  try {
    await categoryStore.loadCategories()
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 显示密码生成器
const showPasswordGenerator = () => {
  generatorPopup.value?.open()
}

// 使用生成的密码
const useGeneratedPassword = (password: string) => {
  formData.value.password = password
  generatorPopup.value?.close()
}

// 密码生成回调
const onPasswordGenerated = (password: string) => {
  // 可以在这里做一些额外的处理
  console.log('生成密码:', password)
}

// 显示分类选择器
const showCategoryPicker = () => {
  categoryPopup.value?.open()
}

// 隐藏分类选择器
const hideCategoryPicker = () => {
  categoryPopup.value?.close()
}

// 选择分类
const selectCategory = (category: Category) => {
  selectedCategory.value = category
  formData.value.category_id = category.id
  hideCategoryPicker()
}

// 获取分类图标
const getCategoryIcon = (iconName?: string): string => {
  const iconMap: Record<string, string> = {
    'social': '👥',
    'shopping': '🛒',
    'work': '💼',
    'finance': '💰',
    'entertainment': '🎮',
    'education': '📚',
    'health': '🏥',
    'travel': '✈️',
    'food': '🍔',
    'sports': '⚽',
    'music': '🎵',
    'photo': '📷',
    'tools': '🔧',
    'security': '🔒',
    'communication': '📞',
    'news': '📰',
    'weather': '🌤️',
    'maps': '🗺️',
    'productivity': '📊',
    'lifestyle': '🌟',
    'other': '📁'
  }

  return iconMap[iconName || 'other'] || '📁'
}

// 显示日期选择器
const showDatePicker = () => {
  if (formData.value.expires_at) {
    const date = new Date(formData.value.expires_at)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    datePickerValue.value = [
      years.value.indexOf(year),
      months.value.indexOf(month),
      days.value.indexOf(day)
    ]
  }

  updateDays()
  datePopup.value?.open()
}

// 隐藏日期选择器
const hideDatePicker = () => {
  const year = years.value[datePickerValue.value[0]]
  const month = months.value[datePickerValue.value[1]]
  const day = days.value[datePickerValue.value[2]]

  formData.value.expires_at = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
  datePopup.value?.close()
}

// 清除日期
const clearDate = () => {
  formData.value.expires_at = ''
  datePopup.value?.close()
}

// 日期变化
const onDateChange = (event: any) => {
  datePickerValue.value = event.detail.value
  updateDays()
}

// 格式化日期
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日`
}

// 切换收藏状态
const toggleFavorite = () => {
  formData.value.is_favorite = !formData.value.is_favorite
}

// 处理保存
const handleSave = async () => {
  if (!canSave.value || isLoading.value) return

  try {
    isLoading.value = true

    const data = { ...formData.value }

    // 清理数据
    if (!data.website?.trim()) data.website = ''
    if (!data.username?.trim()) data.username = ''
    if (!data.password?.trim()) data.password = ''
    if (!data.notes?.trim()) data.notes = ''
    if (!data.expires_at?.trim()) data.expires_at = ''

    emit('save', data)

  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}
</script>

<style lang="scss" scoped>
.account-form {
  background: white;
  min-height: 100vh;

  .form-header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;

    .form-title {
      font-size: 18px;
      font-weight: 600;
      color: #1a1a1a;
    }
  }

  .form-content {
    padding: 20px;

    .form-section {
      margin-bottom: 24px;

      .section-title {
        display: block;
        font-size: 16px;
        font-weight: 600;
        color: #1a1a1a;
        margin-bottom: 16px;
      }

      .form-group {
        margin-bottom: 16px;

        .form-label {
          display: block;
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;

          .required {
            color: #ff4d4f;
          }
        }

        .form-input {
          width: 100%;
          padding: 12px 16px;
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          font-size: 16px;

          &::placeholder {
            color: #999;
          }

          &:focus {
            border-color: #1890ff;
            background: white;
          }
        }

        .form-textarea {
          width: 100%;
          height: 80px;
          padding: 12px 16px;
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          font-size: 16px;
          resize: none;

          &::placeholder {
            color: #999;
          }

          &:focus {
            border-color: #1890ff;
            background: white;
          }
        }

        .password-input-wrapper {
          position: relative;

          .password-input {
            padding-right: 80px;
          }

          .password-actions {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            gap: 4px;

            .action-btn {
              width: 32px;
              height: 32px;
              border-radius: 6px;
              background: rgba(24, 144, 255, 0.1);
              display: flex;
              align-items: center;
              justify-content: center;
              transition: all 0.2s;

              .action-icon {
                font-size: 14px;
                color: #1890ff;
              }

              &:active {
                transform: scale(0.9);
                background: rgba(24, 144, 255, 0.2);
              }
            }
          }
        }

        .category-selector,
        .date-selector {
          padding: 12px 16px;
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          transition: all 0.2s;

          &:active {
            border-color: #1890ff;
            background: white;
          }

          .category-text,
          .date-text {
            font-size: 16px;
            color: #333;

            &.placeholder {
              color: #999;
            }
          }

          .selector-arrow {
            font-size: 18px;
            color: #666;
            transform: rotate(90deg);
          }
        }

        .form-switches {
          .switch-item {
            padding: 12px 16px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.2s;

            &:active {
              transform: scale(0.98);
              background: #e9ecef;
            }

            .switch-label {
              font-size: 16px;
              color: #333;
            }

            .switch-icon {
              font-size: 18px;
            }
          }
        }
      }
    }
  }

  .form-footer {
    padding: 20px;
    display: flex;
    gap: 12px;
    border-top: 1px solid #f0f0f0;

    button {
      flex: 1;
      padding: 14px;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      transition: all 0.2s;

      &:active {
        transform: scale(0.98);
      }

      &:disabled {
        opacity: 0.6;
        transform: none !important;
      }
    }

    .cancel-btn {
      background: #f6f6f6;
      color: #666;
    }

    .save-btn {
      background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
      color: white;
    }
  }

  .category-picker,
  .date-picker {
    background: white;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    max-height: 60vh;

    .picker-header {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .picker-title {
        font-size: 16px;
        font-weight: 600;
        color: #1a1a1a;
      }

      .picker-close,
      .picker-action {
        color: #1890ff;
        font-size: 14px;
      }
    }

    .picker-content {
      max-height: 300px;
      padding: 8px 0;

      .category-option {
        padding: 12px 20px;
        display: flex;
        align-items: center;
        gap: 12px;
        transition: all 0.2s;

        &.active {
          background: rgba(24, 144, 255, 0.05);
        }

        &:active {
          background: #f0f0f0;
        }

        .category-icon {
          font-size: 20px;
        }

        .category-name {
          flex: 1;
          font-size: 16px;
          color: #333;
        }

        .selected-icon {
          color: #1890ff;
          font-size: 16px;
        }
      }
    }

    .picker-view {
      height: 200px;

      .picker-item {
        display: flex;
        align-items: center;
        justify-content: center;

        text {
          font-size: 16px;
          color: #333;
        }
      }
    }
  }

  .generator-popup {
    width: 90vw;
    max-width: 400px;
    max-height: 80vh;
    border-radius: 16px;
    overflow: hidden;
  }
}
</style>